/**
 * 主功能：路径查找
 */
const Router = require('@koa/router');
const {
  Map,
  // MapWay,
} = require('../../db/schemas')

// const { Language } = require('../../env');
const mapRedix = require('../../redis/map-way');
const { genResponse } = require('../../utils')

const router = new Router({ prefix: '/public' })

/** 构建邻接表 */
async function buildAdjacencyList() {
  const maps = await Map.find({}, 'mapID to').lean();
  const graph = {};

  maps.forEach(({ mapID, to }) => {
    graph[mapID] = to.map(item => item.mapID);
  });

  await mapRedix.setGraph(JSON.stringify(graph), 3600)
  return graph;
}
/** BFS路径查找算法 */
async function findSinglePath(start, end, graph) {
  if (start === end) return [start];

  const queue = [[start]];
  const visited = new Set([start]);

  while (queue.length > 0) {
    const path = queue.shift();
    const lastNode = path[path.length - 1];

    for (const neighbor of graph[lastNode] || []) {
      if (neighbor === end) {
        return [...path, neighbor];
      }

      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push([...path, neighbor]);
      }
    }
  }
  return null;
}

router.get('/map-way', async (ctx) => {
  const { start, end } = ctx.query
  const graph = await (mapRedix.getGraph() || buildAdjacencyList())
  const path = findSinglePath(start, end, graph)

  if (path) {
    ctx.body = genResponse(true, { path: path.join('->') })
  } else {
    ctx.body = genResponse(false, null, '没有找到路径')
  }
})


module.exports = router